﻿using Coldairarrow.Entity.PB;
using Coldairarrow.IBusiness;
using Coldairarrow.Util;
using EFCore.Sharding;
using LinqKit;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace Coldairarrow.Business.PB
{
    public partial class PB_UnloadBillBusiness : BaseBusiness<PB_UnloadBill>, IPB_UnloadBillBusiness, ITransientDependency
    {
        readonly IOperator _operator;
        public PB_UnloadBillBusiness(IDbAccessor db, IOperator @operator)
            : base(db)
        {
            _operator = @operator;
        }

        #region 外部接口

        public async Task<PageResult<PB_UnloadBill>> GetDataListAsync(PageInput<ConditionDTO> input)
        {
            var q = GetIQueryable();
            var where = LinqHelper.True<PB_UnloadBill>();
            var search = input.Search;
            if (!input.Search.Keyword.IsNullOrEmpty()) {
                q = q.Where(m=>m.PlateNO.Contains(input.Search.Keyword)||m.UnloadingUserName.Contains(input.Search.Keyword));
            }
           

            return await q.Where(where).GetPageResultAsync(input);
        }

        public async Task<PB_UnloadBill> GetTheDataAsync(string id)
        {
            return await GetEntityAsync(id);
        }

        public async Task AddDataAsync(PB_UnloadBill data)
        {
            await InsertAsync(data);
        }

        public async Task UpdateDataAsync(PB_UnloadBill data)
        {
            await UpdateAsync(data);
        }

        public async Task DeleteDataAsync(List<string> ids)
        {
            await DeleteAsync(ids);
        }

        public async Task<List<PB_UnloadBillPlateNO>> Get_UnloadBillPlateNO()
        {
            StringBuilder sql = new StringBuilder();
            List<PB_UnloadBillPlateNO> pB_UnloadBillPlateNOs = new List<PB_UnloadBillPlateNO>();
            sql.AppendLine("SELECT");
            sql.AppendLine("Id,");
            sql.AppendLine("concat(PlateNO, '(', CreateTime, ')') AS PlateNO");
            sql.AppendLine("FROM");
            sql.AppendLine("PB_TransportBill");
            sql.AppendLine("WHERE");
            sql.AppendLine("ReturnStatus=0");
            sql.AppendLine("AND `State` >= 1");
            sql.AppendLine("AND BillType = 'Return' ");
            pB_UnloadBillPlateNOs =await Db.GetListBySqlAsync<PB_UnloadBillPlateNO>(sql.ToString());
            return pB_UnloadBillPlateNOs;
        }

        public async Task<List<PB_UnloadingDetails>> Get_UnloadingDetails(string Bild)
        {
            var list = new List<PB_UnloadingDetails>();
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.AppendLine("");
           stringBuilder.AppendLine("SELECT");
            stringBuilder.AppendLine("returnlog.ProjectId,");
            stringBuilder.AppendLine("returnlog.BuildingId,");
            stringBuilder.AppendLine("project.`Name` ProjectName,");
            stringBuilder.AppendLine("bulider.Buildingnumber,");
            stringBuilder.AppendLine("IFNULL(SUM(returnlog.ThisReturnNums), 0) AS UnloadingNums,");
            stringBuilder.AppendLine("returnlog.MaterialId AS MaterialId,");
            stringBuilder.AppendLine("mater.`Name` Name,");
            stringBuilder.AppendLine("mater.`Code` Code");
            stringBuilder.AppendLine("FROM");
            stringBuilder.AppendLine("PB_Return AS returnmain");
            stringBuilder.AppendLine("LEFT JOIN PB_ReturnDetailLog AS returnlog ON returnlog.ParentId = returnmain.Id");
            stringBuilder.AppendLine("LEFT JOIN PB_Project AS project ON returnlog.ProjectId = project.Id");
            stringBuilder.AppendLine("LEFT JOIN PB_Buildingnumber AS bulider ON returnlog.BuildingId = bulider.Id");
            stringBuilder.AppendLine("LEFT JOIN PB_Material AS mater ON returnlog.MaterialId = mater.Id");
            stringBuilder.AppendLine("where returnmain.BillId = '"+Bild+"'");
            stringBuilder.AppendLine("GROUP BY");
            stringBuilder.AppendLine("returnlog.ProjectId,");
            stringBuilder.AppendLine("returnlog.BuildingId,");
            stringBuilder.AppendLine("returnlog.MaterialId");
            stringBuilder.AppendLine("ORDER BY returnlog.ProjectId,");
            stringBuilder.AppendLine("returnlog.BuildingId,");
            stringBuilder.AppendLine("returnlog.MaterialId");
            list =await Db.GetListBySqlAsync<PB_UnloadingDetails>(stringBuilder.ToString());
            return list;
        }

        /// <summary>
        /// 回货卸车单保存
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [Transactional]
        public async Task  PB_UnloadBillInfoAdd(PB_UnloadBillInfo data)
        {
            //创建回货卸车明细数据
            string UnloadId = IdHelper.GetId();
            List<PB_UnloadBillDetail> pB_UnloadBillDetails = new List<PB_UnloadBillDetail>();
            for (int i=0;i<data.SubData.Count;i++) {
                //组装明细数据
                PB_UnloadBillDetail pB_UnloadBillDetail = new PB_UnloadBillDetail();
                pB_UnloadBillDetail.Id = IdHelper.GetId();
                pB_UnloadBillDetail.ParentId = UnloadId;
                pB_UnloadBillDetail.ProjectId = data.SubData[i].ProjectId;
                pB_UnloadBillDetail.BuildingId = data.SubData[i].BuildingId;
                pB_UnloadBillDetail.MaterialId = data.SubData[i].MaterialId;
                pB_UnloadBillDetail.UnloadingNums = data.SubData[i].UnloadingNums;
                pB_UnloadBillDetail.CreateTime = DateTime.Now;
                pB_UnloadBillDetail.CreatorId = _operator.UserId;
                pB_UnloadBillDetail.Deleted = false;
                pB_UnloadBillDetails.Add(pB_UnloadBillDetail);
            }
            PB_UnloadBill pB_UnloadBill = new PB_UnloadBill();
            pB_UnloadBill.Id = UnloadId;
            pB_UnloadBill.BillID = data.BillID;
            pB_UnloadBill.UnloadingUserId = data.UnloadingUserId;
            pB_UnloadBill.UnloadingUserName = data.UnloadingUserName;
            pB_UnloadBill.UnloadingState = 0;
            pB_UnloadBill.UnloadingTime = DateTime.Now;
            pB_UnloadBill.UnloadingWeight = data.UnloadingWeight;
            pB_UnloadBill.CreateTime = DateTime.Now;
            pB_UnloadBill.PlateNO = data.PlateNO;
            pB_UnloadBill.CreatorId = _operator.UserId;
            pB_UnloadBill.Deleted = false;
            await Db.InsertAsync<PB_UnloadBillDetail>(pB_UnloadBillDetails);
            await Db.InsertAsync<PB_UnloadBill>(pB_UnloadBill);
            //修改派车单为已回
            string sql = "update PB_TransportBill set  ReturnStatus=1 where Id='"+data.BillID+"'";
            await Db.ExecuteSqlAsync(sql);
        }

        public async Task<PB_UnloadBillMain> pB_UnloadBillMain(string UnloadId)
        {
            PB_UnloadBillMain pB_UnloadBillMain = new PB_UnloadBillMain();
            var PB_UnloadBill =await Db.GetIQueryable<PB_UnloadBill>().Where(m=>m.Id==UnloadId).FirstOrDefaultAsync();
            if (PB_UnloadBill!=null) {
                pB_UnloadBillMain.Id = PB_UnloadBill.Id;
                pB_UnloadBillMain.BillID = PB_UnloadBill.BillID;
                pB_UnloadBillMain.UnloadingUserId = PB_UnloadBill.UnloadingUserId;
                pB_UnloadBillMain.UnloadingUserName = PB_UnloadBill.UnloadingUserName;
                pB_UnloadBillMain.UnloadingState = PB_UnloadBill.UnloadingState;
                pB_UnloadBillMain.UnloadingTime = PB_UnloadBill.UnloadingTime;
                pB_UnloadBillMain.UnloadingWeight = PB_UnloadBill.UnloadingWeight;
                pB_UnloadBillMain.CreateTime = PB_UnloadBill.CreateTime;
                pB_UnloadBillMain.CreatorId = PB_UnloadBill.CreatorId;
                pB_UnloadBillMain.Deleted = PB_UnloadBill.Deleted;
                pB_UnloadBillMain.PlateNO = PB_UnloadBill.PlateNO;

                Expression<Func<PB_UnloadBillDetail, PB_Project, PB_Buildingnumber, PB_Material,PB_UnloadBillDetailDto>> select = (a, b, c,d) => new PB_UnloadBillDetailDto
                {
                    ProjectName = b.Name,
                    Buildingnumber = c.Buildingnumber,
                    Name=d.Name,
                    Code=d.Code,
                };
                select = select.BuildExtendSelectExpre();
                var q = from  a in Db.GetIQueryable<PB_UnloadBillDetail>().AsExpandable()
                        join b in Db.GetIQueryable<PB_Project>() on a.ProjectId equals b.Id into ab
                        from b in ab.DefaultIfEmpty()
                        join c in Db.GetIQueryable<PB_Buildingnumber>() on a.BuildingId equals c.Id into ac
                        from c in ac.DefaultIfEmpty()
                        join d in Db.GetIQueryable<PB_Material>() on a.MaterialId equals d.Id into ad
                        from d in ad.DefaultIfEmpty()
                        select @select.Invoke(a, b, c,d);
                q = q.Where(m=>m.ParentId== PB_UnloadBill.Id);
                pB_UnloadBillMain.Detail = q.ToList();
                return pB_UnloadBillMain;
            }
            return null;
        }

        #endregion

        #region 私有成员

        #endregion
    }
}